package com.cuitrip.business.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.service.R;
import com.lab.app.BaseActivity;

import java.util.ArrayList;
import java.util.List;


/**
 * TODO
 * Created by MiJack on 2015/10/22.
 */
public class CountryPageSelectActivity extends BaseActivity {
    public static final String KEY_RESULT = "KEY_RESULT";
    public static final String KEY_CODE="KEY_CODE";
    CountryAdapter countryAdapter;
    LinearLayout layout;
    ViewGroup searchBox;
    EditText searchView;
    ListView listView;
    IconTextView searchIcon;
    List<CountryModel> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_country_page_select);
        layout = (LinearLayout) findViewById(R.id.layout);
        listView = (ListView) findViewById(R.id.listView);
        searchBox = (ViewGroup) findViewById(R.id.search_box);
        searchIcon = (IconTextView) findViewById(R.id.searchIcon);
        searchView = (EditText) findViewById(R.id.searchView);
        searchView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    searchIcon.setVisibility(View.GONE);
                } else {
                    searchIcon.setVisibility(View.VISIBLE);
                }
            }
        });
        searchBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (searchView.getVisibility() == View.INVISIBLE) {
                    searchView.setVisibility(View.VISIBLE);
                }
            }
        });
        searchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String newText = s.toString();
                if (TextUtils.isEmpty(newText)) {
                    countryAdapter.getFilter().filter(newText);
                } else {
                    countryAdapter.getFilter().filter(newText);
                }
            }
        });
        String[] array = getResources().getStringArray(R.array.country_list);
        list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            CountryModel countryModel = CountryModel.fromString(array[i]);
            list.add(countryModel);
            //判断是否为新的key
            if (i == 0 || !list.get(i - 1).key.equals(countryModel.key)) {
                TextView textView = new TextView(this);
                textView.setText(countryModel.key);
                final int position = i;
                textView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        listView.setSelection(position);
                        return true;
                    }
                });
                layout.addView(textView);
            }
        }
        setResult(RESULT_CANCELED);
        countryAdapter = new CountryAdapter(list);
        listView.setAdapter(countryAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CountryModel item = countryAdapter.getItem(position);
                setResult(RESULT_OK, new Intent().putExtra(KEY_RESULT, item.countryName).putExtra(KEY_CODE,item.countryCode));
                finish();
            }
        });
    }


    public class CountryAdapter extends BaseAdapter implements Filterable {
        private List<CountryModel> list;

        public CountryAdapter(List<CountryModel> list) {
            this.list = list;
        }

        public void setData(Object data) {
            this.list = (List<CountryModel>) data;
            this.notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public CountryModel getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_country, parent, false);
                holder = new ViewHolder();
                holder.keyView = (TextView) convertView.findViewById(R.id.tvKey);
                holder.countryCodeView = (TextView) convertView.findViewById(R.id.tvCode);
                holder.countryNameView = (TextView) convertView.findViewById(R.id.tvName);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            CountryModel model = getItem(position);
            if (position == 0 || !getItem(position).key.equals(getItem(position - 1).key)) {
                holder.keyView.setVisibility(View.VISIBLE);
            } else {
                holder.keyView.setVisibility(View.GONE);
            }
            holder.keyView.setText(model.key);
            holder.countryCodeView.setText(model.countryCode);
            holder.countryNameView.setText(model.countryName);
            return convertView;
        }

        @Override
        public Filter getFilter() {
            if (filter == null) {
                filter = new CountryModelFilter(this);
            }
            return filter;
        }


        class ViewHolder {
            TextView keyView;
            TextView countryCodeView;
            TextView countryNameView;
        }

        CountryModelFilter filter;
    }

    class CountryModelFilter extends Filter {
        private CountryPageSelectActivity.CountryAdapter countryAdapter;

        public CountryModelFilter(CountryPageSelectActivity.CountryAdapter countryAdapter) {
            this.countryAdapter = countryAdapter;
        }

        @Override
        // 该方法在子线程中执行
        // 自定义过滤规则
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            List<CountryModel> newValues = new ArrayList<>();
            String filterString = constraint.toString().trim()
                    .toLowerCase();

            // 如果搜索框内容为空，就恢复原始数据
            if (TextUtils.isEmpty(filterString)) {
                newValues = list;
            } else {
                // 过滤出新数据
                for (CountryModel model : list) {
                    if (model.countryName.contains(filterString)) {
                        newValues.add(model);
                    }
                }
            }

            results.values = newValues;
            results.count = newValues.size();

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            countryAdapter.setData(results.values);
        }
    }

    static class CountryModel {
        public String key;
        public String countryCode;
        public String countryName;

        @Override
        public String toString() {
            return "CountryModel{" +
                    "key='" + key + '\'' +
                    ", countryCode='" + countryCode + '\'' +
                    ", countryName='" + countryName + '\'' +
                    '}';
        }

        public static CountryModel fromString(String value) {
            CountryModel countryModel = new CountryModel();
            countryModel.key = value.charAt(0) + "";
            String[] t = value.split("\\+");
            countryModel.countryCode = "+" + t[1];
            countryModel.countryName = t[0];
            return countryModel;
        }
    }
}